package com.mall.interceptor;

import com.mall.constant.JwtClaimsConstant;
import com.mall.context.BaseContext;
import com.mall.properties.JwtProperties;
import com.mall.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 管理端拦截器
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class AdminInterceptor implements HandlerInterceptor {

    private final JwtProperties properties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader(properties.getAdminTokenName());
        try {
            Claims claims = JwtUtil.parseJWT(properties.getAdminSecretKey(), token);
            log.info("token校验通过: {}", token);
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            log.info("当前员工id为: {}", empId);
            BaseContext.setCurrentId(empId);
            return true;
        } catch (Exception e) {
            log.error("token校验失败");
            response.setStatus(401);
            return false;
        }
    }
}
